#include "trackballcamera.h"
#include "sdlglutils.h"
#include "graphisme.h"
#include "module.h"

#include "echiquier.h"
#include "piece.h"
#include "jeu.h"

#include <fmod/fmod.h>
#include <iostream>
#include <cmath>

#include <SDL/SDL_ttf.h>

using namespace std;

int puissance2sup(int i)
{
    double logbase2 = log(i) / log(2);
    return (int) floor(pow(2.0, ceil(logbase2)));
}

GLfloat blackMaterial2[] = {0.0, 0.0, 0.0,1};

void ecrit_texte(string text, TTF_Font *font, SDL_Color color, SDL_Rect *location)
{
	glBegin(GL_QUADS);
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, blackMaterial2);
	glVertex3d(3,3,3);
	glVertex3d(3,3,-3);
	glVertex3d(-3,3,-3);
	glVertex3d(-3,3,3);
	glEnd();
	
	glDisable(GL_LIGHTING);
	glBlendFunc(GL_ONE,GL_ONE);
	glDisable(GL_TEXTURE_2D);
	glEnable2D();
	glDisable(GL_DEPTH_TEST);
	
	SDL_GL_RenderText(text, font, color, location);

	glEnable(GL_DEPTH_TEST);
	glDisable2D();
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_LIGHTING);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	return ;	
}


double angleZ = 0;
double angleX = 0;

GLfloat whiteMaterial[] = {1.0, 1, 1,1};

GLuint texture = loadTexture("text.jpg");

int LightPos[4] = {0,0,1000,1};
int MatSpec [4] = {1,1,1,1};
//~ float LightDif[4] = {.5f,.5f,1.f,1.f};
//~ glDepthMask(GL_TRUE);
Echiquier e;

TrackBallCamera *camera; 

int main(int argc, char *argv[])
{
	e.initialise();
	
	//init de la musique
	/*************************************************************************************************************************************/
	FMOD_SYSTEM *system;
    FMOD_SOUND *musique;
    FMOD_RESULT resultat;

    
    FMOD_System_Create(&system);
    FMOD_System_Init(system, 1, FMOD_INIT_NORMAL, NULL);

    /* On ouvre la musique */
    resultat = FMOD_System_CreateSound(system, "Musique/1.mp3",FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
		//FMOD_HARDWARE | FMOD_2D | FMOD_CREATESTREAM

    /* On vérifie si elle a bien été ouverte (IMPORTANT) */
    if (resultat != FMOD_OK)
    {
        cout << "Impossible de lire le fichier mp3\n"<<endl;
        return 1;
    }

    /* On joue la musique */
    FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, musique, 0, NULL);
    
    
    //init des graphismes
    /*************************************************************************************************************************************/  
	int screen_w = 1024;
	int screen_h = 768;
	
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    
    glEnable(GL_TEXTURE_2D);
    atexit(SDL_Quit);
    SDL_WM_SetCaption("Echiquier 3D", NULL);
    SDL_Surface * ecran;
    ecran = SDL_SetVideoMode(screen_w, screen_h, 32, SDL_OPENGL);
    
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(70,(double)screen_w/screen_h,1,1000);    

    glEnable(GL_DEPTH_TEST);
   	glEnable(GL_BLEND); //active la transparence
   	glEnable(GL_MODULATE);
   	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  
   
    //bidouille d'éclairage
	glEnable(GL_LIGHTING); 	// Active l'éclairage
  	glEnable(GL_LIGHT0); 	// Allume la lumière n°1
  	//~ glLightfv(GL_LIGHT0,GL_DIFFUSE,LightDif);
	glLightiv(GL_LIGHT0,GL_POSITION,LightPos);
	
	glClearColor(1,1,1,0); //met le fond en blanc

	//init des polices
	/*************************************************************************************************************************************/	
		TTF_Init();
		atexit(TTF_Quit);
		
		TTF_Font* Font = TTF_OpenFont("angelina.ttf", 60);
		SDL_Color color;
		SDL_Rect position;
		
		color.r = 0;
		color.g = 0;
		color.b = 255;
		
		position.x = screen_w / 3;
		position.y = screen_h / 2;

	/*************************************************************************************************************************************/
	
	camera = new TrackBallCamera();
    camera->setScrollSensivity(0.5);

    const Uint32 time_per_frame = 20;

    Uint32 last_time,current_time; //for time animation
    Uint32 stop_time; //for frame limit
    
	GLUquadric* params = gluNewQuadric();
		
	//~ gluQuadricTexture(params, GL_TRUE);
	
	
	vector <int> test1;
	vector<int> test2;
	bool espace = false;

	for (;;)
		{
		//start_time = SDL_GetTicks();
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT: 
                stop(camera);
                gluDeleteQuadric(params);
                FMOD_Sound_Release(musique);
				FMOD_System_Close(system);
				FMOD_System_Release(system);
				TTF_CloseFont(Font); /* Doit être avant TTF_Quit() */
				//~ TTF_Quit(); //dans atexit()
                exit(0);
                break;
                
                case SDL_KEYDOWN:
                switch (event.key.keysym.sym)
                {
                    case SDLK_p: //à corriger : ne prend pas en compte la source de lumière
                    takeScreenshot("test.bmp");
                    break;
                    case SDLK_ESCAPE:
                    stop(camera);
					gluDeleteQuadric(params);
					FMOD_Sound_Release(musique);
					FMOD_System_Close(system);
					FMOD_System_Release(system);
					TTF_CloseFont(Font); /* Doit être avant TTF_Quit() */
					//~ TTF_Quit();
                    exit(0);
                    break;         
                    case SDLK_SPACE:
					if (espace)
					{
						test1.clear();
						test2.clear();
						espace = false;
					}
					else
					{
						espace = true;
						zones_couvertes(&test1, &test2, &e);
					}
                    break;
                    default : //on a utilisé la touche P et la touche ECHAP, le reste est donné à la caméra
                    camera->OnKeyboard(event.key);
                }
                break;
                
                case SDL_MOUSEMOTION: //la souris est bougée, ça n'intéresse que la caméra
                camera->OnMouseMotion(event.motion);
                break;
                case SDL_MOUSEBUTTONUP:
                case SDL_MOUSEBUTTONDOWN:
                camera->OnMouseButton(event.button); //tous les événements boutons (up ou down) sont donnés à la caméra
                break;
            }
		}

		current_time = SDL_GetTicks();
        last_time = current_time;		

		init_dessin(camera);	
		e.trace(params, camera);
		//~ fin_dessin();
	
///////////////////////////////////////////////////////////////////
		
		ecrit_texte("test pour voir", Font, color, &position);

////////////////////////////////////////////////////////////////////////////////

		if (espace)
		{
			dessin_zone(&test1);			
			//~ dessin_zone(&test2);
		}
		
		fin_dessin();
		
		stop_time = SDL_GetTicks();
        if ((stop_time - last_time) < time_per_frame)
        {
            SDL_Delay(time_per_frame - (stop_time - last_time));
        }
    }


    return 0;
}
